'use strict';
const mongoose =require('mongoose');

/**
 * mongoose 分页查询插件
 */
function pageQueryPlugin(schema) {

    /**
     *
     * @param paginationOption 分页配置参数 default value : {page:0,pageSize:25}
     * @param populate
     * @param queryParams 查询条件
     * @param fields 子段
     * @param sortParams 排序参数
     * @param callback 回调函数 function(err,results)
     * @returns {Promise<{pagination: {page: number|*, pageSize: *|number, rowCount: number, pageCount: number}, data: Array}>}
     */
    schema.statics.findPage = async function (paginationOption, populate, queryParams, fields, sortParams,lean=false) {

        const Model = this; //mongoose Model's static method
        const page = Number(paginationOption.page || pageQueryPlugin.defaultPaginationOption.page);
        const pageSize = Number(paginationOption.pageSize || pageQueryPlugin.defaultPaginationOption.pageSize);
        const start = (page - 1) * pageSize;

        let $page = { //初始化
            pagination: {
                page: page,
                pageSize: pageSize,
                rowCount: 0,
                pageCount: 0
            },
            data: []
        };

        try {

            let count = await Model.count(queryParams).exec();
            if (count > 0) {
                $page.pagination.rowCount = count;
                $page.pagination.pageCount = Math.ceil((count - 1) / pageSize + 1);

                // if (!think.isEmpty(populate)){
                //     console.log(populate)
                //     const populates= populate.trim().split(' ');
                //     for(let item of populates ) {
                //         item=item.trim();
                //         if (!think.isEmpty(item)){
                //             console.log(item)
                //             think.mongoose(item);//强制加载
                //         }
                //     }
                // }

                let records = await Model.find(queryParams,null,{lean:lean}).skip(start).limit(pageSize)
                    .populate(populate).select(fields).sort(sortParams).exec();
                $page.data= records;
                // $page.data= JSON.parse(data.toJSON());

            }
        } catch (err) {
            console.log(err);
        }
        return $page;
    }
}

pageQueryPlugin.defaultPaginationOption = {
    page: 1,
    pageSize: 10
};

/**
 * @param {Schema} schema
 */
module.exports = pageQueryPlugin;